Imports System.Data
Imports BlazeApps.Library.Form
Imports AjaxControlToolkit

Partial Class Usercontrols_Form_Form
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Protected Property FormGuid() As Guid
        Get
            Return GetGuidFromVS("FormID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("FormID", value)
        End Set
    End Property

    Protected Property FormQuestionGuid() As Guid
        Get
            Return GetGuidFromVS("FormQuestionID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("FormQuestionID", value)
        End Set
    End Property

    Protected Property FormEditMode() As Boolean
        Get
            Return GetBooleanFromVS("FormEditMode")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("FormEditMode", value)
        End Set
	End Property

	Protected Property OtherOptionSelected() As Boolean
		Get
			Return GetBooleanFromVS("OtherOptionSelected")
		End Get
		Set(ByVal value As Boolean)
			ViewState.Add("OtherOptionSelected", value)
		End Set
	End Property

	Protected Property OtherOptionID() As Guid
		Get
			Return GetGuidFromVS("OtherOptionID")
		End Get
		Set(ByVal value As Guid)
			ViewState.Add("OtherOptionID", value)
		End Set
	End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.MessageLabel = Me.uxMessagesLabel
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SetPageTitle("")
		GetQueryStringValues()

		Dim item As FormDetail = FormDetail.GetFormDetail(FormGuid)

		If item.RegisteredUserOnly And IsUserAuthenticated = False Then
			Me.uxFormPanel.Visible = False
			Me.uxFormPanel.Enabled = False
			Me.uxMessagesLabel.Text = "You must be a registered site user to access this form."
		Else
			BuildPage(FormGuid, Guid.Empty, Me.uxControlsPlaceHolder, "formsystem", False, False)
		End If

    End Sub

#End Region

#Region " Save Data "

    Private Sub SaveFormFields()
        If Page.IsValid() Then
            Try
                Dim tablecontrol As Control

                Dim response As FormResponse = FormResponse.NewFormResponse()

                response.FormID = FormGuid

                If IsUserAuthenticated() Then
                    response.TakenBy = CurrentUser()
                Else
                    response.TakenBy = Resources.Resource.Anonymous
                End If

                response.Save()

                'Loop through the table to access the rows added
                For Each tablecontrol In Me.uxControlsPlaceHolder.Controls

                    Dim rowcontrol As Control

                    'Loop through the rows in the table to access the cells added
                    For Each rowcontrol In tablecontrol.Controls

                        Dim cellcontrol As Control

                        'Loop through the second cell added to the rows, as that is where our data control resides
                        'Index of 0 is always the question lable, not need to access it.
                        'Index of 1 is always going to be the control we need to get data from
						For Each cellcontrol In rowcontrol.Controls(0).Controls

							If TypeOf cellcontrol Is Table Then

								Dim table As Table = DirectCast((cellcontrol), Table)
								Dim row As New TableRow

								For Each row In table.Rows

									If row.ID.ToString().EndsWith("RowChoice") Then

										Dim cell As TableCell

										For Each cell In row.Cells

											Dim ctl As New Control

											For Each ctl In cell.Controls

												If TypeOf ctl Is RadioButton And ctl.ID.ToString().EndsWith("RadioButton") Then
													Dim rb As RadioButton = DirectCast((ctl), RadioButton)

													If rb.Checked Then

														Dim id() As String

														id = Split(rb.ID, "_")

														Dim QuestionGuid As New Guid
														Dim RowGuid As New Guid
														Dim ColumnGuid As New Guid

														QuestionGuid = ConvertToGuid(id(1).ToString().Trim())
														RowGuid = ConvertToGuid(id(2).ToString().Trim())
														ColumnGuid = ConvertToGuid(id(3).ToString().Trim())

														Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.NewFormAnswerRowColumnDetail()

														MultiItem.FormResponseID = response.FormResponseID
														MultiItem.FormQuestionID = QuestionGuid
														MultiItem.FormRowID = RowGuid
														MultiItem.FormColumnID = ColumnGuid

														MultiItem.IsSelected = True
														MultiItem.Save()

													End If

												End If

												If TypeOf ctl Is CheckBox And ctl.ID.ToString().EndsWith("CheckBox") Then
													Dim cb As CheckBox = DirectCast((ctl), CheckBox)

													If cb.Checked Then

														Dim id() As String

														id = Split(cb.ID, "_")

														Dim QuestionGuid As New Guid
														Dim RowGuid As New Guid
														Dim ColumnGuid As New Guid

														QuestionGuid = ConvertToGuid(id(1).ToString().Trim())
														RowGuid = ConvertToGuid(id(2).ToString().Trim())
														ColumnGuid = ConvertToGuid(id(3).ToString().Trim())

														Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.NewFormAnswerRowColumnDetail()

														MultiItem.FormResponseID = response.FormResponseID
														MultiItem.FormQuestionID = QuestionGuid
														MultiItem.FormRowID = RowGuid
														MultiItem.FormColumnID = ColumnGuid
														MultiItem.IsSelected = True
														MultiItem.Save()

													End If

												End If

											Next

										Next

									End If

								Next

							End If

							If Not (TypeOf cellcontrol Is Image OrElse TypeOf cellcontrol Is AjaxControlToolkit.CalendarExtender OrElse TypeOf cellcontrol Is HtmlTable) Then
								Dim Item As FormAnswerDetail = FormAnswerDetail.NewFormAnswerDetail()

								Dim id() As String
								Dim OtherOptionText As String = String.Empty

								id = Split(cellcontrol.ID, "_")

								Dim QuestionGuid As New Guid
								QuestionGuid = ConvertToGuid(id(1).ToString().Trim())

								Dim QuestionDetail As FormQuestionDetail = FormQuestionDetail.GetFormQuestionDetail(QuestionGuid)
								Dim ControlDetail As FormControlsDetail = FormControlsDetail.GetFormControlsDetail(QuestionDetail.FormControlID)

								If QuestionDetail.IsOtherOption Then
									OtherOptionText = QuestionDetail.OtherOptionText
								End If

								If TypeOf cellcontrol Is RadioButtonList Then
									Dim rbl As RadioButtonList = DirectCast((cellcontrol), RadioButtonList)
									Dim li As New ListItem

									Select Case ControlDetail.ControlType
										Case FormControlType.MultipleChoiceSingleAnswer

											For Each li In rbl.Items
												If li.Selected Then
													Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.NewFormAnswerRowColumnDetail()
													MultiItem.FormResponseID = response.FormResponseID
													MultiItem.FormQuestionID = QuestionGuid
													MultiItem.FormRowID = ConvertToGuid(li.Value.ToString().Trim())

													If li.Text.Trim.ToUpper.Equals(OtherOptionText.Trim.ToUpper) And QuestionDetail.IsOtherOption Then
														OtherOptionSelected = True
														OtherOptionID = QuestionGuid
													End If

													MultiItem.IsSelected = True
													MultiItem.Save()
												End If
											Next

										Case FormControlType.MatrixOneAnswerPerRow

									End Select

								End If

								If TypeOf cellcontrol Is CheckBoxList Then
									Dim cbl As CheckBoxList = DirectCast((cellcontrol), CheckBoxList)
									Dim li As New ListItem

									Select Case ControlDetail.ControlType
										Case FormControlType.MultipleChoiceMultipleAnswer

											For Each li In cbl.Items
												If li.Selected Then
													Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.NewFormAnswerRowColumnDetail()
													MultiItem.FormResponseID = response.FormResponseID
													MultiItem.FormQuestionID = QuestionGuid
													MultiItem.FormRowID = ConvertToGuid(li.Value.ToString().Trim())

													If li.Text.Trim.ToUpper.Equals(OtherOptionText.Trim.ToUpper) And QuestionDetail.IsOtherOption Then
														OtherOptionSelected = True
														OtherOptionID = QuestionGuid
													End If

													MultiItem.IsSelected = True
													MultiItem.Save()
												End If
											Next

										Case FormControlType.MatrixMultipleAnswersPerRow

									End Select

								End If

								If TypeOf cellcontrol Is DropDownList Then
									Dim ddl As DropDownList = DirectCast((cellcontrol), DropDownList)

									Select Case ControlDetail.ControlType
										Case FormControlType.SelectionList
											Dim MultiItem As FormAnswerRowColumnDetail = FormAnswerRowColumnDetail.NewFormAnswerRowColumnDetail()
											MultiItem.FormResponseID = response.FormResponseID
											MultiItem.FormQuestionID = QuestionGuid
											MultiItem.FormRowID = ConvertToGuid(ddl.SelectedValue.ToString().Trim())
											MultiItem.IsSelected = True
											MultiItem.Save()
									End Select

								End If

								If TypeOf cellcontrol Is TextBox Then
									Dim txt As TextBox = DirectCast((cellcontrol), TextBox)

									Select Case ControlDetail.ControlType
										Case FormControlType.SingleTextBox
											Item.FormResponseID = response.FormResponseID
											Item.FormQuestionID = QuestionGuid
											Item.Answer = txt.Text.ToString().Trim()
											Item.Save()
										Case FormControlType.MultilineTextBox
											Item.FormResponseID = response.FormResponseID
											Item.FormQuestionID = QuestionGuid
											Item.Answer = txt.Text.ToString().Trim()
											Item.Save()
										Case FormControlType.DateTimeBox
											Item.FormResponseID = response.FormResponseID
											Item.FormQuestionID = QuestionGuid
											Item.Answer = txt.Text.ToString().Trim()
											Item.Save()
										Case FormControlType.MultipleChoiceSingleAnswer
											If OtherOptionSelected And OtherOptionID = QuestionGuid Then
												Item.FormResponseID = response.FormResponseID
												Item.FormQuestionID = QuestionGuid
												Item.Answer = txt.Text.ToString().Trim()
												Item.Save()

												OtherOptionSelected = False
												OtherOptionID = Guid.Empty
											End If
										Case FormControlType.MultipleChoiceMultipleAnswer
											If OtherOptionSelected And OtherOptionID = QuestionGuid Then
												Item.FormResponseID = response.FormResponseID
												Item.FormQuestionID = QuestionGuid
												Item.Answer = txt.Text.ToString().Trim()
												Item.Save()

												OtherOptionSelected = False
												OtherOptionID = Guid.Empty
											End If
									End Select

								End If

							End If

						Next

                    Next

                Next
            Catch ex As Exception
                'Not going to do anything here at the moment.
                Throw ex
            Finally
                ShowCompletionMessage()
            End Try

        End If
    End Sub

#End Region

#Region " Load Data "

#End Region

#Region " Form Controls Events "

    Protected Sub uxSaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxSaveButton.Click
        SaveFormFields()
    End Sub

#End Region

#Region " Helpers and Methods "

    Protected Sub GetQueryStringValues()
        FormGuid = GetGuidFromQueryString("FormID")
    End Sub

    Private Sub ShowCompletionMessage()
        Me.uxFormPanel.Visible = False
        Me.uxFormCompletePanel.Visible = True

        Dim formDetail As FormDetail = formDetail.GetFormDetail(FormGuid)

        Me.uxCompleteMessageLabel.Text = formDetail.FormCompleteMessage
    End Sub

#End Region

End Class
